package com.example.thread;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * @author YDF
 * @date 2019/12/31
 */
public class Master {
    private ConcurrentLinkedQueue<Task> taskQueue = new ConcurrentLinkedQueue<>();
    private ConcurrentHashMap<String, Object> resultMap = new ConcurrentHashMap<>();
    private Map<String, Thread> workerMap = new HashMap<>();

    public Master(Worker worker, int workerCount) {
        worker.setResultMap(resultMap);
        worker.setTaskQueue(taskQueue);
        for (int i = 0; i < workerCount; i++) {
            workerMap.put("worker" + i, new Thread(worker));
        }
    }

    public void submit(Task task) {
        this.taskQueue.add(task);
    }

    /**
     * 开始执行任务
     */
    public void execute() {
        for (Map.Entry<String, Thread> entry : workerMap.entrySet()) {
            entry.getValue().start();
        }
    }

    /**
     * 是否全部执行完成
     *
     * @return
     */
    public boolean isCompleted() {
        for (Map.Entry<String, Thread> entry : workerMap.entrySet()) {
            if (entry.getValue().getState() != Thread.State.TERMINATED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 获取结果
     *
     * @return
     */
    public int getResult() {
        int result = 0;
        for (Map.Entry<String, Object> entry : resultMap.entrySet()) {
            result = (int) entry.getValue();
        }
        return result;
    }
}
